using AutoMapper;
using B.S.XZYData.Api.Read.Application.Command.Plan;
using B.S.XZYData.Api.Read.Dto.Plan;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.Plan
{
    /// <summary>
    /// 获取产品选择列表处理器
    /// </summary>
    public class GetProductSelectHandler : IRequestHandler<GetProductSelectCommand, ApiPageing<ProductSelectDto>>
    {
        private readonly IBaseRepository<ProductModel> _productRepo;
        private readonly IMapper _mapper;

        public GetProductSelectHandler(
            IBaseRepository<ProductModel> productRepo,
            IMapper mapper)
        {
            _productRepo = productRepo;
            _mapper = mapper;
        }

        public async Task<ApiPageing<ProductSelectDto>> Handle(GetProductSelectCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiPageing<ProductSelectDto>();

            try
            {
                // 构建查询条件
                var query = _productRepo.GetAll();

                // 产品编号模糊查询
                if (!string.IsNullOrWhiteSpace(request.ProductCode))
                {
                    query = query.Where(x => x.Code.Contains(request.ProductCode));
                }

                // 产品名称模糊查询
                if (!string.IsNullOrWhiteSpace(request.ProductName))
                {
                    query = query.Where(x => x.Name.Contains(request.ProductName));
                }

                // 排序（按产品编号）
                query = query.OrderBy(x => x.Code);

                // 获取总数
                var totalCount = query.Count();

                // 分页
                var products = query
                    .Skip((request.Index - 1) * request.Size)
                    .Take(request.Size)
                    .ToList();

                // 映射到DTO
                var productSelectDtos = _mapper.Map<List<ProductSelectDto>>(products);

                res.PageData = productSelectDtos;
                res.TotaCount = totalCount;
                res.TotaPage = (int)Math.Ceiling((double)totalCount / request.Size);
                res.Code = ApiEnum.Success;
                res.Msg = "获取产品选择列表成功";
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"获取产品选择列表失败：{ex.Message}";
            }

            return res;
        }
    }
} 